/*******************************************************************************
 * Level Master 2000
 * Copyright (C) 2010 Christian Herzog
 * For more information see http://code.google.com/p/levelmaster2000/
 *
 * This file is licensed under the terms of the MIT license, see
 * http://www.opensource.org/licenses/mit-license.php for further information.
 ******************************************************************************/

#include "DeleteEntityCommand.h"

#include <QUndoCommand>
#include <QStringList>

#include "../EntityExplorer.h"
#include "../Entity.h"
#include "../LevelMaster2000.h"

DeleteEntityCommand::DeleteEntityCommand( EntityExplorer* entityExplorer,
                     QString name,
                     QString group,
                     QString entityXML,
                     QUndoCommand *parent )
                         : QUndoCommand( parent ),
                         entityExplorer( entityExplorer ),
                         name( name ),
                         group( group ),
                         entityXML( entityXML )
{
    init();
}

void DeleteEntityCommand::init()
{
    setText( "Delete Entity \"" + name + "\"" );
    selectedEntitiesAtCreation = entityExplorer->selectedEntities();

    int idx = -1;

    for( int i = 0; i < selectedEntitiesAtCreation.size(); i++ )
    {
        if( selectedEntitiesAtCreation[i]->name == name )
        {
            idx = i;
            break;
        }
    }

    if(idx != -1)
    {
        selectedEntitiesAtCreation.removeAt(idx);
    }
}

void DeleteEntityCommand::undo()
{
    LevelMaster2000::DISALLOW_NEW_COMMAND++;
    {
        entityExplorer->createEntity( name, group );
        entityExplorer->setEntityXml( name, entityXML );
        entityExplorer->tree->clearSelection();

        QList<Entity*> selectedEntities;

        if( entityExplorer->findEntity( name ) )
        {
            selectedEntities << entityExplorer->findEntity( name );
        }

        selectedEntities << selectedEntitiesAtCreation;
        entityExplorer->addEntitiesToSelection( selectedEntities );

        entityExplorer->updateLastSelection();
    }
    LevelMaster2000::DISALLOW_NEW_COMMAND--;
}

void DeleteEntityCommand::redo()
{
    LevelMaster2000::DISALLOW_NEW_COMMAND++;
    {
        entityExplorer->removeEntityFromSelection( entityExplorer->findEntity( name ) );
        entityExplorer->updateLastSelection();
        entityExplorer->deleteEntity( name );
    }
    LevelMaster2000::DISALLOW_NEW_COMMAND--;
}
